<template>
  <div>
    <!-- textContent存在就是普通文本，如果不存在就是下拉文本 -->
    <el-tooltip
      v-if="showTitle"
      effect="dark"
      placement="top-start"
    >
      <template v-if="selectData.list && selectData.list.length !== 0">
        <div slot="content">
          {{ getSelectTextFn() }}
        </div>
        <span
          class="my-input-sc"
        >
        {{ getSelectTextFn() }}
        </span>
      </template>
      <template v-else>
        <div slot="content">
          {{ textContent }}
        </div>
        <span
          class="my-input-sc"
        >
        {{ textContent }}
        </span>
      </template>
    </el-tooltip>
    <span
      v-else
      class="my-input-sc"
      @mouseover="handleMouseOver"
    >
      <template v-if="selectData.list && selectData.list.length !== 0">
        {{ getSelectTextFn() }}
      </template>
      <template v-else>
        {{ textContent }}
      </template>
    </span>
  </div>
</template>
<script>
export default {
  props: {
    textContent: { // 对象是下拉框之外的组件文本内容
      type: [String, Number],
      default: ''
    },
    selectData: { // 对象是下拉框的数据集合
      type: Object,
      default () {
        return {
          val: '', // 当前value
          list: [], // options集合
          valueName: 'value', // 绑定的value名称，默认'value'
          labelName: 'label' // 绑定的label名称，默认'label'
        }
      }
    }
  },
  data () {
    return {
      showTitle: false // 是否显示toolTip
    }
  },
  methods: {
    /* select下拉框value对应label的回显方法 */
    getSelectTextFn () {
      let { list, val, valueName, labelName } = this.selectData;
      let result = val;
      let target = _.find(list, (item) => {
        return item[valueName] === val;
      });
      if (target) {
        result = target[labelName];
      }
      return result;
    },
    /* 鼠标移入事件 */
    handleMouseOver (e) {
      let target = e.target;
      let textLength = target.clientWidth; // 文本内容长度
      let boxLength = target.scrollWidth; // 文本容器长度
      if (textLength < boxLength) { // 内容溢出，显示toolTip
        this.showTitle = true;
      } else { // 内容没有溢出，不显示toolTip
        this.showTitle = false;
      }
    }
  }
}
</script>
<style lang="less" scoped>
/* 虚假input框样式 */
.my-input-sc {
  display: inline-block;
  height: 30px;
  line-height: 30px;
  -webkit-appearance: none;
  background-color: #FFFFFF;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
  box-sizing: border-box;
  color: #606266;
  font-size: inherit;
  outline: none;
  padding: 0 15px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
  vertical-align:middle;
}
</style>
